/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.renren.common.utils.EBPUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisKeys;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.SysDictEntity;
import io.renren.modules.sys.entity.SysDictTextValueEntity;
import io.renren.modules.sys.redis.SysDictRedis;
import io.renren.modules.sys.service.SysDictService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据字典
 *
 * @author Mark sunlightcs@gmail.com
 * @since 3.1.0 2018-01-27
 */
@RestController
@RequestMapping("sys/dict")
public class SysDictController {
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysDictRedis sysDictRedis;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:dict:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = sysDictService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 页面获取所有字典
     */
    @RequestMapping({"/select"})
    public R select() {
        String types;
        String key = RedisKeys.getSysDictKey("*");
        Set<String> keySet = sysDictRedis.getKeys(key);
        types = StringUtils.join(keySet, ",");
        System.out.println("redis中获取字典key列表" + types);
        if (null == types || "".equals(types)) {
            return selectForDB();
        } else {
            return select(types.replaceAll(RedisKeys.getSysDictKey(""), ""));
        }
    }

    /**
     * 页面获取所有字典
     */
    @RequestMapping({"/select/{types}"})
    public R select(@PathVariable("types") String types) {
        System.out.println("获取字典信息：" + types);
        Map<String, Object> map = new HashMap<>();

        String[] typeArr = types.split(",");
        for (String type : typeArr) {
            List<String> dicList = sysDictRedis.getDictList(type);
            if (CollectionUtils.isEmpty(dicList)) {
                //从数据中查询字典数据
                Wrapper<SysDictEntity> sysDictEntityWrapper = new EntityWrapper<>();
                sysDictEntityWrapper.eq("type", type);
                sysDictEntityWrapper.orderBy("order_num");
                List<SysDictEntity> sysDictEntities = sysDictService.selectList(sysDictEntityWrapper);
                sysDictRedis.pushDictAllData(sysDictEntities);
                dicList = sysDictRedis.getDictList(type);
            }
            List<SysDictTextValueEntity> sortedCollection = dicList.parallelStream()
                    .map(dicJsonStr -> EBPUtils.fromJson(dicJsonStr, SysDictTextValueEntity.class))
                    .sorted(Comparator.comparing(SysDictTextValueEntity::getOrderNum))
                    .collect(Collectors.toList());
            map.put(type, sortedCollection);
        }
        return R.ok().put("dict", map);
    }

    /**
     * 页面获取所有字典
     */
    private R selectForDB() {
        Map<String, List<SysDictTextValueEntity>> map = new HashMap<>();
        if (null == map || map.size() == 0) {
            System.err.println("获取字典信息为空,无数据或未启用redis,切换为读取数据库");
            List<SysDictEntity> list = sysDictService.selectList(new EntityWrapper<SysDictEntity>().orderBy("type").orderBy("order_num"));
            List<SysDictTextValueEntity> dc = new ArrayList<>();
            for (Iterator it = list.iterator(); it.hasNext(); ) {
                SysDictEntity dict = (SysDictEntity) it.next();
                SysDictTextValueEntity tv = new SysDictTextValueEntity();
                tv.setText(dict.getValue());
                tv.setValue(dict.getCode());
                dc.add(tv);
                if (map.containsKey(dict.getType())) { //如果已经存在这个数组，就放在这里
                    List tvList = map.get(dict.getType());
                    tvList.add(tv);
                } else {
                    List tvList = new ArrayList();  //重新声明一个数组list
                    tvList.add(tv);
                    map.put(dict.getType(), tvList);
                }
            }
        }
        return R.ok().put("dict", map);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:dict:info")
    public R info(@PathVariable("id") Long id) {
        SysDictEntity dict = sysDictService.selectById(id);

        return R.ok().put("dict", dict);
    }

    /**
     * 将字典表插入redis
     */
    public R pushDictAllData() {
        List<SysDictEntity> list = sysDictService.selectList(new EntityWrapper<SysDictEntity>().orderBy("type").orderBy("order_num"));
        sysDictRedis.pushDictAllData(list);
        return R.ok();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:dict:save")
    public R save(@RequestBody SysDictEntity dict) {
        //校验类型
        ValidatorUtils.validateEntity(dict);

        sysDictService.insert(dict);
        sysDictRedis.saveOrUpdate(dict);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:dict:update")
    public R update(@RequestBody SysDictEntity dict) {
        //校验类型
        ValidatorUtils.validateEntity(dict);

        sysDictService.updateById(dict);
        sysDictRedis.saveOrUpdate(dict);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:dict:delete")
    public R delete(@RequestBody Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            System.out.println(ids[i]);
            SysDictEntity dict = sysDictService.selectById(ids[i]);
            sysDictRedis.delete(dict.getType(), dict.getCode());
        }
        sysDictService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

}
